#include "history.h"
#include "ui_history.h"
#include"downloadimage.h"

#include <QTableView>// 显示数据表

#include<QDebug>

#include <QFileDialog>
#include <QDesktopServices>
#include <QMessageBox>
#include <QAxObject>

#include"waiting.h"
#include<QFuture>
#include<QtConcurrent>

//字符编码设为utf-8
//#pragma execution_character_set("utf-8")


history::history(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::history)
{

    ui->setupUi(this);
    this->userName=login::Qname;
    //    ui->widget_show_images->setStyleSheet("border-width: 1px;border-style: solid;border-color: rgb(255, 170, 0);");
    //设置窗口图标
    //    this->setWindowIcon(QIcon(":/images/软件图标.png"));

    //选中表格
    //    QModelIndex index = ui->tableView->selectionModel()->currentIndex();
    //    int iSel = index.row();

    ui->tableView->setSelectionBehavior ( QAbstractItemView::SelectRows); //选择以行为单位
    ui->tableView->setSelectionMode ( QAbstractItemView::SingleSelection);//设置选择模式，选择单行

    model_ = new QSqlQueryModel;//用来展示
    query=new QSqlQuery;//用来得到结果的
    qDebug()<<"history: username="<<userName;


    //如果是医生，仅展示医生检测的；如果是管理员，则展示所有的检测记录
    QString sql_user="select role from user where user_name='"+this->userName+"'";
    QString sql_user_id="select user_id from user where user_name='"+this->userName+"'";
    query->exec(sql_user);
    query->next();
    QString user_role=query->value(0).toString();

    if(user_role==QStringLiteral("医生")){
        query->exec(sql_user_id);
        query->next();
        QString user_id=QString::number(query->value(0).toInt());
        //没有排序的
        sql_slect_no_order="select distinct record.record_id,ct.Diagnosis_number,ct.picture,user.user_name,record.detecting_result,record.create_time,record.update_time from ct,record,user where ct.ct_id=record.ct_id and record.user_id=user.user_id and record.user_id="+user_id;
         //根据时间倒叙
        sql_slect_="select distinct record.record_id,ct.Diagnosis_number,ct.picture,user.user_name,record.detecting_result,record.create_time,record.update_time from ct,record,user where ct.ct_id=record.ct_id and record.user_id=user.user_id and record.user_id="+user_id+" ORDER BY record.update_time DESC";
    }
    else{
        //没有排序的
        sql_slect_no_order="select distinct record.record_id,ct.Diagnosis_number,ct.picture,user.user_name,record.detecting_result,record.create_time,record.update_time from ct,record,user where ct.ct_id=record.ct_id and record.user_id=user.user_id";
         //根据时间倒叙
        sql_slect_="select distinct record.record_id,ct.Diagnosis_number,ct.picture,user.user_name,record.detecting_result,record.create_time,record.update_time from ct,record,user where ct.ct_id=record.ct_id and record.user_id=user.user_id ORDER BY record.update_time DESC";

    }

    model_->setQuery(sql_slect_);
    //end


    model_->setHeaderData(0,Qt::Horizontal,QStringLiteral("记录号"));
    model_->setHeaderData(1,Qt::Horizontal,QStringLiteral("就诊号"));
    model_->setHeaderData(2,Qt::Horizontal,QStringLiteral("图片地址"));
    model_->setHeaderData(3,Qt::Horizontal,QStringLiteral("检测医生"));
    model_->setHeaderData(4,Qt::Horizontal,QStringLiteral("检测结果"));
    model_->setHeaderData(5,Qt::Horizontal,QStringLiteral("创建时间"));
    model_->setHeaderData(6,Qt::Horizontal,QStringLiteral("修改时间"));


    ui->tableView->setModel(model_);
    //设置第一列为固定80宽度，其他自适应

    ui->tableView->setColumnWidth(0, 100);
    ui->tableView->hideColumn(0);//隐藏第0行
    ui->tableView->hideColumn(2);//隐藏第2行，图片地址
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    ui->tableView->resizeColumnsToContents();

    //交替行颜色
    ui->tableView->setAlternatingRowColors(true);






}

history::~history()
{
    delete ui;
    delete model_;
    delete query;
}

//刷新表格数据
void history::flash()
{
    //用于刷新数据，暂时没有找到更好的方法，根据时间倒叙
    model_->setQuery(sql_slect_);
}




//删除选定行
void history::on_pushButton_clicked()
{

    QModelIndex index=ui->tableView->currentIndex();//获取当前选择行的index
    qDebug()<<"delete:"<<index.row();
    //没有选中，则不进行任何操作
    if(index.row()!=-1)
    {
        //获取选择行的record_id
        qDebug()<<"record_id="<<model_->data(model_->index(index.row(),0)).toInt();
        QString record_id=model_->data(model_->index(index.row(),0)).toString();
        //query执行。。
        query->exec("delete from record where record_id="+record_id);


        //用于刷新数据，暂时没有找到更好的方法，根据时间倒叙
        model_->setQuery(sql_slect_);

    }
    else {
        QMessageBox::warning(NULL, QStringLiteral("删除失败"), QStringLiteral("请选择要删除的记录"));
    }



}

//根据就诊号查询查询
void history::on_pushButton_check_by_id_clicked()
{

    QString edit=ui->lineEdit_id->text();
    qDebug()<<edit;
    int number=edit.toUInt();
    QString numberStr=QString::number(number);
    qDebug()<<"number="<<number;
    if(number==0)
    {
        QMessageBox::warning(NULL, QStringLiteral("查询结果失败"), QStringLiteral("请输入正确的就诊号"));
        model_->setQuery(sql_slect_);
    }
    else {
        QString tempSql= sql_slect_no_order+" and Diagnosis_number="+numberStr+" ORDER BY record.update_time DESC";
        qDebug()<<"查询sql："<<tempSql;
        //查询的结果有多少条
        query->exec(tempSql);
        qDebug()<<QStringLiteral("查询结果共有：")<<query->size();

        if(query->size()!=0){
            model_->setQuery(tempSql);
        }
        else {

            QMessageBox::warning(NULL, QStringLiteral("查询结果失败"), QStringLiteral("未找到相关记录"));

            model_->setQuery(sql_slect_);

        }
    }


}
//导出结果表格
void history::on_pushButton_export_table_clicked()
{
    QString title=QStringLiteral("结直肠息肉检测记录");
    QString fileName = QFileDialog::getSaveFileName(ui->tableView, QStringLiteral("保存"),QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),QStringLiteral("Excel 文件(*.xls *.xlsx)"));
    if (fileName!="")
    {
        QAxObject *excel = new QAxObject;
        if (excel->setControl("Excel.Application")) //连接Excel控件
        {
            excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
            excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示
            QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
            workbooks->dynamicCall("Add");//新建一个工作簿
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
            QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

            int i,j;

            //                 QTableView 获取列数
            int colount=ui->tableView->model()->columnCount();
            //                 QTableView 获取行数
            int rowcount=ui->tableView->model()->rowCount();

            QAxObject *cell,*col;
            //标题行
            cell=worksheet->querySubObject("Cells(int,int)", 1, 1);
            cell->dynamicCall("SetValue(const QString&)", title);
            cell->querySubObject("Font")->setProperty("Size", 18);
            //调整行高
            worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
            //合并标题行
            QString cellTitle;
            cellTitle.append("A1:");
            cellTitle.append(QChar(colount - 1 + 'A'));
            cellTitle.append(QString::number(1));
            QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle);
            range->setProperty("WrapText", true);
            range->setProperty("MergeCells", true);
            range->setProperty("HorizontalAlignment", -4108);//xlCenter
            range->setProperty("VerticalAlignment", -4108);//xlCenter
            //列标题
            for(i=0;i<colount;i++)
            {
                QString columnName;
                columnName.append(QChar(i  + 'A'));
                columnName.append(":");
                columnName.append(QChar(i + 'A'));
                col = worksheet->querySubObject("Columns(const QString&)", columnName);
                col->setProperty("ColumnWidth", ui->tableView->columnWidth(i)/6);
                cell=worksheet->querySubObject("Cells(int,int)", 2, i+1);
                //QTableWidget 获取表格头部文字信息
                //                columnName=table->horizontalHeaderItem(i)->text();
                //QTableView 获取表格头部文字信息
                columnName=ui->tableView->model()->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString();
                cell->dynamicCall("SetValue(const QString&)", columnName);
                cell->querySubObject("Font")->setProperty("Bold", true);
                cell->querySubObject("Interior")->setProperty("Color",QColor(191, 191, 191));
                cell->setProperty("HorizontalAlignment", -4108);//xlCenter
                cell->setProperty("VerticalAlignment", -4108);//xlCenter
            }

            //数据区

            //QTableWidget 获取表格数据部分
            //            for(i=0;i<rowcount;i++){
            //                for (j=0;j<colount;j++)
            //                {
            //                    worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", table->item(i,j)?table->item(i,j)->text():"");
            //                }
            //            }


            //QTableView 获取表格数据部分
            for(i=0;i<rowcount;i++) //行数
            {
                for (j=0;j<colount;j++)   //列数
                {
                    QModelIndex index = ui->tableView->model()->index(i, j);
                    QString strdata=ui->tableView->model()->data(index).toString();
                    worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", strdata);
                }
            }


            //画框线
            QString lrange;
            lrange.append("A2:");
            lrange.append(colount - 1 + 'A');
            lrange.append(QString::number(ui->tableView->model()->rowCount() + 2));
            range = worksheet->querySubObject("Range(const QString&)", lrange);
            range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
            range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));
            //调整数据区行高
            QString rowsName;
            rowsName.append("2:");
            rowsName.append(QString::number(ui->tableView->model()->rowCount() + 2));
            range = worksheet->querySubObject("Range(const QString&)", rowsName);
            range->setProperty("RowHeight", 20);
            workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至fileName
            workbook->dynamicCall("Close()");//关闭工作簿
            excel->dynamicCall("Quit()");//关闭excel
            delete excel;
            excel=NULL;
            if (QMessageBox::question(NULL,QStringLiteral("完成"),QStringLiteral("文件已经导出，是否现在打开？"),QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
            {
                QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
            }
        }
        else
        {
            QMessageBox::warning(NULL,QStringLiteral("错误"),QStringLiteral("未能创建 Excel 对象，请安装 Microsoft Excel。"),QMessageBox::Apply);
        }
    }
}

//选中并查看图片，跳转界面到result
void history::on_pushButton_look_clicked()
{
    //先从数据库中得到，然后下载到本地，这个就是本地图片地址.
    //如何判别是否重复？判断下载文件夹是否含有该图片，如果有则不下载，如果没有则下载到本地。名字就为数据库中保存的图片。或者分割一下

    QString url;
    QString localPathImage;
    QModelIndex index=ui->tableView->currentIndex();//获取当前选择行的index
    qDebug()<<"delete:"<<index.row();
    //没有选中，则不进行任何操作
    if(index.row()!=-1)
    {
        qDebug()<<"record_id="<<model_->data(model_->index(index.row(),0)).toInt();
        QString record_id=model_->data(model_->index(index.row(),0)).toString();
        //query执行。。
        query->exec("select picture from ct where ct.ct_id in (select ct_id from record where record_id="+record_id+")");
        //获取结果集
        query->next();
        QString url=query->value(0).toString();
        qDebug()<<"history:url->"<<url;
        //图片命名
//        localPathImage=QDir::currentPath()+"/network/"+record_id+".jpg";
        QString path=setting::downloadPath;
        makeDirPath(path);
        localPathImage=path+"/"+record_id+".jpg";
        DownloadImage *download=new DownloadImage;
        //下载图片


        //需要判断文件夹中是否已经存在了
        //
        //信息查看
        //界面相关
        result *resLook=new result;
        TitleBar *tBar=new TitleBar;
        tBar->setAttribute(Qt::WA_DeleteOnClose, true);
        tBar->setMainWidget(resLook);
        tBar->setTitleBarText(QStringLiteral("历史记录查看"));
        connect(this,SIGNAL(sendData(QString,QString,bool)),resLook,SLOT(getOutputImageName(QString,QString,bool)));
        QFileInfo file(localPathImage);
        if(file.exists()){
            qDebug()<<"history: file has exist!";
            qDebug()<<"history: localpathimage->"<<localPathImage;

            //判断该图片是否可用
            QImage* img=new QImage;
            if(!(img->load(localPathImage)))
            {
                QMessageBox::warning(NULL,QStringLiteral("图片打开失败"),QStringLiteral("打开图片文件失败！%1,请重新查看图片").arg(localPathImage));
                QFile::remove(localPathImage);
                delete img;
            }
            else{
                //从数据库中获取message
        //        int num_detect=1;//从数据库中得到
                //query执行。。
                query->exec("select detecting_result from record where record_id="+record_id);
                //获取结果集
                query->next();
                QString message=query->value(0).toString();

                emit sendData(localPathImage,message,false);

                tBar->show();
            }





        }
        else {
            qDebug()<<"history: file not exist!";

            //异步加载等待界面
//            download->startDownload(url,localPathImage);
            Waiting pWait(this);
            pWait.show();
            QFuture<void> fut=QtConcurrent::run([=]()->void{ return
                       download->startDownload(url,localPathImage);}); //异步处理        while(!future.isFinished())
            while(!fut.isFinished())
            {
                QApplication::processEvents(QEventLoop::AllEvents, 100);//唤醒主界面
            }
            pWait.close();



            if(download->isSuccess){
                qDebug()<<"history: localpathimage->"<<localPathImage;
                //判断该图片是否可用
                QImage* img=new QImage;
                if(!(img->load(localPathImage)))
                {
                    QMessageBox::warning(NULL,QStringLiteral("图片打开失败"),QStringLiteral("打开图片文件失败！%1,请重新查看图片").arg(localPathImage));
                    QFile::remove(localPathImage);
                    delete img;
                }
                else{
                    //从数据库中获取message
            //        int num_detect=1;//从数据库中得到
                    //query执行。。
                    query->exec("select detecting_result from record where record_id="+record_id);
                    //获取结果集
                    query->next();
                    QString message=query->value(0).toString();
                    emit sendData(localPathImage,message,false);

                    tBar->show();
                }

            }
            else {
                QMessageBox::warning(NULL, QStringLiteral("查看失败"), QStringLiteral("获取图片失败，请重试"));
            }
        }


        delete download;

    }
    else{
        QMessageBox::warning(NULL, QStringLiteral("查看失败"), QStringLiteral("请选择要查看的记录"));
    }

}

bool history::makeDirPath(QString dirPath)
{
    QString dest=dirPath;
    QDir dir;
    if(!dir.exists(dest))
    {
        dir.mkpath(dest);
        return true;
    }
    else
    {
        return false;
    }
}
